<?php

namespace app\common\model;
use think\Model;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 数据层模型
 */
class Order extends Model {
    public $page_info;
    

    /**
     * 取单条订单信息
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @param array $extend 扩展
     * @param string $fields 字段
     * @param array $order 排序
     * @param array $group 分组
     * @return array
     */
    public function getOrderInfo($condition = array(), $extend = array(), $fields = '*,o.order_sn as order_sns', $order = '', $group = '') {
        $order_info = db('order')->alias('o')
           ->join('app_order ao','ao.app_order_id=o.apporder_id')
          ->field($fields)->where($condition)->group($group)->order($order)->find();
        if (empty($order_info)) {
            return array();
        }
        // 是否发货
        if (isset($order_info['order_state'])) {
            $order_info['state_desc'] = get_order_state($order_info);
        }
        // 付款状态
        if (isset($order_info['payment_code'])) {
            $order_info['payment_name'] = get_order_payment_name($order_info['payment_code']);
        }
        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_info['extend_order_common'] = $this->getOrdercommonInfo(array('order_id' => $order_info['order_id']));
            $order_info['extend_order_common']['reciver_info'] = unserialize($order_info['extend_order_common']['reciver_info']);
            $order_info['extend_order_common']['invoice_info'] = unserialize($order_info['extend_order_common']['invoice_info']);
        }

        //追加返回店铺信息
        if (in_array('store', $extend)) {
            $order_info['extend_store'] = model('store')->getStoreInfo(array('store_id' => $order_info['store_id']));
        }

        //返回买家信息
        if (in_array('member', $extend)) {
            $order_info['extend_member'] = model('member')->getMemberInfoByID($order_info['buyer_id']);
        }
        //追加返回商品信息  order_goods表信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = $this->getOrdergoodsList(array('order_id' => $order_info['order_id']));
            $order_info['extend_order_goods'] = $order_goods_list;
        }
        
        //追加返回拼团订单信息
        if (in_array('ppintuanorder', $extend)) {
            //取拼团订单附加列表
            $pintuanorder_list = model('ppintuanorder')->getPpintuanorderList(array('ppintuanorder.order_id' => $order_info['order_id']));
            if (!empty($pintuanorder_list)) {
                foreach ($pintuanorder_list as $value) {
                    $order_info['pintuan_id'] = $value['pintuan_id'];
                    $order_info['pintuangroup_id'] = $value['pintuangroup_id'];
                    $order_info['pintuanorder_state'] = $value['pintuanorder_state'];
                    $order_info['pintuanorder_state_text'] = $value['pintuanorder_state_text'];
                }
            }
        }
        return $order_info;
    }
    
    /**
     * 获取订单信息
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @param string $field 字段
     * @return array
     */
    public function getOrdercommonInfo($condition = array(), $field = '*') {
        return db('ordercommon')->where($condition)->find();
    }
    
    /**
     * 获取订单信息
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return type
     */
    public function getOrderpayInfo($condition = array()) {
        return db('orderpay')->where($condition)->find();
    }

    /**
     * 取得支付单列表
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @param string $filed 字段
     * @param string $order 排序
     * @param string $key 以哪个字段作为下标,这里一般指pay_id
     * @return array
     */
    public function getOrderpayList($condition,  $filed = '*', $order = '', $key = '') {
        $pay_list = db('orderpay')->field($filed)->where($condition)->order($order)->select();
        if($key){
            $pay_list = ds_change_arraykey($pay_list, $key);
        }
        return $pay_list;
    }

    /**
     * 取得订单列表(未被删除)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getNormalOrderList($condition, $page = '', $field = '*', $order = 'order_id desc', $limit = '', $extend = array()) {
        $condition['delete_state'] = 0;
        return $this->getOrderList($condition, $page, $field, $order, $limit, $extend);
    }

    /**
     * 取得订单列表(所有)   原来的
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getOrderList($condition, $page = '', $field = '*', $order = 'order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('order')->field($field)->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('order')->field($field)->where($condition)->order($order)->limit($limit)->select();
        }

        if (empty($list))
            return array();
        $order_list = array();
        foreach ($list as $order) {
            if (isset($order['order_state'])) {
                $order['state_desc'] = get_order_state($order);
            }
            if (isset($order['payment_code'])) {
                $order['payment_name'] = get_order_payment_name($order['payment_code']);
            }
            if (!empty($extend))
                $order_list[$order['order_id']] = $order;
        }
        if (empty($order_list))
            $order_list = $list;
        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_common_list = $this->getOrdercommonList(array('order_id' => array('in', array_keys($order_list))));
            foreach ($order_common_list as $value) {
                $order_list[$value['order_id']]['extend_order_common'] = $value;
                $order_list[$value['order_id']]['extend_order_common']['reciver_info'] = @unserialize($value['reciver_info']);
                $order_list[$value['order_id']]['extend_order_common']['invoice_info'] = @unserialize($value['invoice_info']);
            }
        }
        //追加返回店铺信息
        if (in_array('store', $extend)) {
            $store_id_array = array();
            foreach ($order_list as $value) {
                if (!in_array($value['store_id'], $store_id_array))
                    $store_id_array[] = $value['store_id'];
            }
            $store_list = db('store')->where('store_id', 'in', array_values($store_id_array))->select();
            $store_new_list = array();
            foreach ($store_list as $store) {
                $store_new_list[$store['store_id']] = $store;
            }
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_store'] = isset($store_new_list[$order['store_id']])?$store_new_list[$order['store_id']]:'';
            }
        }

        //追加返回买家信息
        if (in_array('member', $extend)) {
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_member'] = model('member')->getMemberInfoByID($order['buyer_id']);
            }
        }


        //追加返回商品信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = db('ordergoods')->where('order_id', 'in', array_keys($order_list))->select();

            if (!empty($order_goods_list)) {
                foreach ($order_goods_list as $value) {

                    $order_list[$value['order_id']]['extend_order_goods'][] = $value;
                }
            } else {
                $order_list[$value['order_id']]['extend_order_goods']= array();
            }
        }
        
        //追加返回拼团订单信息
        if (in_array('ppintuanorder', $extend)) {
            //取拼团订单附加列表
            $pintuanorder_list = model('ppintuanorder')->getPpintuanorderList(array('ppintuanorder.order_id' => array('in', array_keys($order_list))));
            if (!empty($pintuanorder_list)) {
                foreach ($pintuanorder_list as $value) {
                    $order_list[$value['order_id']]['pintuan_id'] = $value['pintuan_id'];
                    $order_list[$value['order_id']]['pintuangroup_id'] = $value['pintuangroup_id'];
                    $order_list[$value['order_id']]['pintuanorder_state'] = $value['pintuanorder_state'];
                    $order_list[$value['order_id']]['pintuanorder_state_text'] = $value['pintuanorder_state_text'];
                }
            }
        }

        return $order_list;
    }


    /**
     * 取得订单列表(所有)   运营商查询大订单id使用
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function supplier_getOrderList($condition, $page = '', $field = 'o.*,a.order_sn as app_order_sn', $order = 'o.order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('order')->alias('o')->join('app_order a','o.apporder_id = a.app_order_id','LEFT')->field($field)->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('order')->alias('o')->join('app_order a','o.apporder_id = a.app_order_id','LEFT')->field($field)->where($condition)->order($order)->limit($limit)->select();
        }
        if (empty($list))
            return array();
        $order_list = array();
        foreach ($list as $order) {
            if (isset($order['order_state'])) {
                $order['state_desc'] = get_order_state($order);
            }
            if (isset($order['payment_code'])) {
                $order['payment_name'] = get_order_payment_name($order['payment_code']);
            }
            if (!empty($extend))
                $order_list[$order['order_id']] = $order;
        }
        if (empty($order_list))
            $order_list = $list;
        //追加返回订单扩展表信息
        if (in_array('order_common', $extend)) {
            $order_common_list = $this->getOrdercommonList(array('order_id' => array('in', array_keys($order_list))));
            foreach ($order_common_list as $value) {
                $order_list[$value['order_id']]['extend_order_common'] = $value;
                $order_list[$value['order_id']]['extend_order_common']['reciver_info'] = @unserialize($value['reciver_info']);
                $order_list[$value['order_id']]['extend_order_common']['invoice_info'] = @unserialize($value['invoice_info']);
            }
        }
        //追加返回店铺信息
        if (in_array('store', $extend)) {
            $store_id_array = array();
            foreach ($order_list as $value) {
                if (!in_array($value['store_id'], $store_id_array))
                    $store_id_array[] = $value['store_id'];
            }
            $store_list = db('store')->where('store_id', 'in', array_values($store_id_array))->select();
            $store_new_list = array();
            foreach ($store_list as $store) {
                $store_new_list[$store['store_id']] = $store;
            }
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_store'] = isset($store_new_list[$order['store_id']])?$store_new_list[$order['store_id']]:'';
            }
        }

        //追加返回买家信息
        if (in_array('member', $extend)) {
            foreach ($order_list as $order_id => $order) {
                $order_list[$order_id]['extend_member'] = model('member')->getMemberInfoByID($order['buyer_id']);
            }
        }


        //追加返回商品信息
        if (in_array('order_goods', $extend)) {
            //取商品列表
            $order_goods_list = db('ordergoods')->where('order_id', 'in', array_keys($order_list))->select();

            if (!empty($order_goods_list)) {
                foreach ($order_goods_list as $value) {

                    $order_list[$value['order_id']]['extend_order_goods'][] = $value;
                }
            } else {
                $order_list[$value['order_id']]['extend_order_goods']= array();
            }
        }

        //追加返回拼团订单信息
        if (in_array('ppintuanorder', $extend)) {
            //取拼团订单附加列表
            $pintuanorder_list = model('ppintuanorder')->getPpintuanorderList(array('ppintuanorder.order_id' => array('in', array_keys($order_list))));
            if (!empty($pintuanorder_list)) {
                foreach ($pintuanorder_list as $value) {
                    $order_list[$value['order_id']]['pintuan_id'] = $value['pintuan_id'];
                    $order_list[$value['order_id']]['pintuangroup_id'] = $value['pintuangroup_id'];
                    $order_list[$value['order_id']]['pintuanorder_state'] = $value['pintuanorder_state'];
                    $order_list[$value['order_id']]['pintuanorder_state_text'] = $value['pintuanorder_state_text'];
                }
            }
        }

        return $order_list;
    }




    /**
     * 取得订单列表(所有)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getapp_OrderList($condition, $page = '', $field = 'ds_app_order.*', $order = 'ds_app_order.app_order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('app_order')->join('invoice','invoice.app_order_id=ds_app_order.app_order_id','LEFT')->field($field)->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('app_order')->field($field)->where($condition)->order($order)->limit($limit)->select();
        }

       if (empty($list))
            return array();
        $order_list = array();
        if (empty($order_list))
            $order_list = $list;
        return  $order_list;
    }

        /**
     * 取得订单列表(所有)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getInvoiceList($condition, $page = '', $order = 'app_order.app_order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('invoice')->alias('i')
                        ->join('app_order','i.app_order_id=app_order.app_order_id')
                        ->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
                        
            
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('app_order')->field($field)->where($condition)->order($order)->limit($limit)->select();
        }

       if (empty($list))
            return array();
        $order_list = array();
        if (empty($order_list))
            $order_list = $list;
        return  $order_list;
    }

            /**
     * 取得订单列表(所有)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function getServiceInvoiceList($condition, $page = '', $order = 's_order.order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('invoice')->alias('i')
                        ->join('s_order','i.app_order_id=s_order.order_id')
                        ->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('app_order')->field($field)->where($condition)->order($order)->limit($limit)->select();
        }

       if (empty($list))
            return array();
        $order_list = array();
        if (empty($order_list))
            $order_list = $list;
        return  $order_list;
    }



    /**
     * 取得(买/卖家)订单某个数量缓存
     * @access public
     * @author csdeshang
     * @param string $type 买/卖家标志，允许传入 buyer、store
     * @param int $id   买家ID、店铺ID
     * @param string $key 允许传入  NewCount、PayCount、SendCount、EvalCount、TradeCount，分别取相应数量缓存，只许传入一个
     * @return array
     */
    public function getOrderCountCache($type, $id, $key) {
        if (!config('cache_open')) return ;
        $types = $id.'_ordercount' .'_'.$type.'_'. $key;
        $count = rcache($types);
        return $count;
    }

    /**
     * 设置(买/卖家)订单某个数量缓存
     * @access public
     * @author csdeshang
     * @param string $type 买/卖家标志，允许传入 buyer、store
     * @param int $id 买家ID、店铺ID
     * @param int $key 允许传入  NewCount、PayCount、SendCount、EvalCount、TradeCount，分别取相应数量缓存，只许传入一个
     * @param array $count 数据
     * @return type
     */
    public function editOrderCountCache($type, $id, $key,$count) {
        if (!config('cache_open') || empty($type) || !intval($id))
            return;
        $types = $id.'_ordercount'.'_'.$type .'_'. $key;
        wkcache($types, $count);
    }

    /**
     * 取得买卖家订单数量某个缓存
     * @access public
     * @author csdeshang
     * @param string $type $type 买/卖家标志，允许传入 buyer、store
     * @param int $id 买家ID、店铺ID
     * @param string $key 允许传入  NewCount、PayCount、SendCount、EvalCount、TradeCount，分别取相应数量缓存，只许传入一个
     * @return int
     */
    public function getOrderCountByID($type, $id, $key) {
        $cache_info = $this->getOrderCountCache($type, $id, $key);
        if (config('cache_open') && is_numeric($cache_info)) {
            //从缓存中取得
            $count = $cache_info;
        } else {
            //从数据库中取得
            $field = $type == 'buyer' ? 'buyer_id' : 'store_id';
            $condition = array($field => $id);
            $func = 'getOrderState' . $key;
            $count = $this->$func($condition);
            $this->editOrderCountCache($type, $id, $key,$count);
        }
        return $count;
    }

    /**
     * 删除(买/卖家)订单全部数量缓存
     * @access public
     * @author csdeshang
     * @param string $type 买/卖家标志，允许传入 buyer、store
     * @param int $id   买家ID、店铺ID
     * @return bool
     */
    public function delOrderCountCache($type, $id) {
        $type_NewCount = $id.'_ordercount' . '_'.$type.'_NewCount';
        $type_PayCount = $id.'_ordercount' . '_'.$type.'_PayCount';
        $type_SendCount = $id.'_ordercount' . '_'.$type.'_SendCount';
        $type_EvalCount = $id.'_ordercount' . '_'.$type.'_EvalCount';
        $type_TradeCount = $id.'_ordercount' . '_'.$type.'_TradeCount';
        dcache($type_NewCount);
        dcache($type_PayCount);
        dcache($type_SendCount);
        dcache($type_EvalCount);
        dcache($type_TradeCount);
    }

    /**
     * 待付款订单数量
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateNewCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_NEW;
        return $this->getOrderCount($condition);
    }

    /**
     * 待发货订单数量
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStatePayCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_PAY;
        return $this->getOrderCount($condition);
    }

    /**
     * 待收货订单数量
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateSendCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_SEND;
        return $this->getOrderCount($condition);
    }

    /**
     * 待评价订单数量
     * @access public
     * @author csdeshang
     * @param type $condition 检索条件
     * @return type
     */
    public function getOrderStateEvalCount($condition = array()) {
        $condition['order_state'] = ORDER_STATE_SUCCESS;
        $condition['evaluation_state'] = 0;
		$condition['refund_state'] = 0;
        return $this->getOrderCount($condition);
    }

    /**
     * 交易中的订单数量
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return int
     */
    public function getOrderStateTradeCount($condition = array()) {
        $condition['order_state'] = array(array('neq', ORDER_STATE_CANCEL), array('neq', ORDER_STATE_SUCCESS), 'and');
        return $this->getOrderCount($condition);
    }

    /**
     * 取得订单数量
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @return int
     */
    public function getOrderCount($condition) {
        return db('order')->where($condition)->count();
    }

    /**
     * 取得订单商品表详细信息
     * @access public
     * @author csdeshang
     * @param array $condition 条件  
     * @param string $fields 字段  
     * @param string $order 排序
     * @return array
     */
    public function getOrdergoodsInfo($condition = array(), $fields = '*', $order = '') {
        return db('ordergoods')->where($condition)->field($fields)->order($order)->find();
    }

    /**
     * 取得订单商品表列表
     * @access public
     * @author csdeshang
     * @param type $condition 条件
     * @param type $fields 字段
     * @param type $limit 限制
     * @param type $page 分页
     * @param type $order 排序
     * @param type $group 分组
     * @param type $key 键
     * @return array
     */
    public function getOrdergoodsList($condition = array(), $fields = '*', $limit = null, $page = null, $order = 'rec_id desc', $group = null, $key = null) {

        if ($page) {
            $res= db('ordergoods')->field($fields)->where($condition)->order($order)->group($group)->paginate($page,false,['query' => request()->param()]);
            $this->page_info=$res;
            $ordergoods = $res->items();
            if(!empty($key)){
                $ordergoods = ds_change_arraykey($ordergoods, $key);
            }
            return $ordergoods;
        } else {
            $ordergoods = db('ordergoods')->field($fields)->where($condition)->limit($limit)->order($order)->group($group)->select();
            if(!empty($key)){
                $ordergoods = ds_change_arraykey($ordergoods, $key);
            }
            return $ordergoods;
        }
    }

    /**
     * 取得订单扩展表列表
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @param string $fields 字段
     * @param string $order 排序
     * @param int $limit 限制
     * @return array
     */
    public function getOrdercommonList($condition = array(), $fields = '*', $order = '', $limit = null) {
        return db('ordercommon')->field($fields)->where($condition)->order($order)->limit($limit)->select();
    }

    /**
     * 插入订单支付表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrderpay($data) {
        return db('orderpay')->insertGetId($data);
    }

    /**
     * 插入订单表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrder($data) {
        $result = db('order')->insertGetId($data);
        if ($result) {
            //更新缓存
            \mall\queue\QueueClient::push('delOrderCountCache',array('buyer_id'=>$data['buyer_id'],'store_id'=>$data['store_id']));
        }
        return $result;
    }


    /**
     * 插入项目定制订单表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrde2($data) {
        $result = db('orderproject')->insertGetId($data);
        
        return $result;
    }

    /**
     * 插入订单扩展表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrdercommon($data) {
        return db('ordercommon')->insertGetId($data);
    }

    /**
     * 插入订单扩展表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrdergoods($data) {
        return db('ordergoods')->insertAll($data);
    }


    /**
     * 插入项目定制订单扩展表信息
     * @access public
     * @author csdeshang
     * @param array $data 参数内容
     * @return int 返回 insert_id
     */
    public function addOrdergoods2($data) {
        return db(' orderproject_goods')->insertAll($data);
    }



    /**
     * 添加订单日志
     * @access public
     * @author csdeshang
     * @param type $data 数据信息
     * @return type
     */
    public function addOrderlog($data) {
        $data['log_role'] = str_replace(array('buyer', 'seller', 'system', 'admin','supply'), array('买家', '商家', '系统', '管理员','供应商'), $data['log_role']);
        $data['log_time'] = TIMESTAMP;
        return db('orderlog')->insertGetId($data);
    }

    /**
     * 添加服务订单日志
     * @access public
     * @author csdeshang
     * @param type $data 数据信息
     * @return type
     */
    public function addSorderlog($data) {
        $data['log_role'] = str_replace(array('buyer', 'seller', 'system', 'admin','supply','service'), array('买家', '商家', '系统', '管理员','供应商','服务人员'), $data['log_role']);
        
        return db('s_order_log')->insertGetId($data);
    }

    /**
     * 更改订单信息
     * @access public
     * @author csdeshang
     * @param array $data 数据
     * @param array $condition 条件
     * @param int $limit 限制
     * @return bool
     */
    public function editOrder($data, $condition, $limit = '') {
        $update = db('order')->where($condition)->limit($limit)->update($data);
        if ($update) {
            //更新缓存
            \mall\queue\QueueClient::push('delOrderCountCache', $condition);
        }
        return $update;
    }

    /**
     * 更改订单信息
     * @access public
     * @author csdeshang
     * @param array $data 数据
     * @param array $condition 条件
     * @return bool
     */
    public function editOrdercommon($data, $condition) {
        return db('ordercommon')->where($condition)->update($data);
    }

    /**
     * 更改订单信息
     * @param unknown_type $data
     * @param unknown_type $condition
     */
    public function editOrdergoods($data, $condition) {
        return db('ordergoods')->where($condition)->update($data);
    }

    /**
     * 更改订单支付信息
     * @access public
     * @author csdeshang
     * @param type $data 数据 
     * @param type $condition 条件
     * @return type
     */
    public function editOrderpay($data, $condition) {
        return db('orderpay')->where($condition)->update($data);
    }

    /**
     * 订单操作历史列表
     * @access public
     * @author csdeshang
     * @param type $condition 条件
     * @return Ambigous <multitype:, unknown>
     */
    public function getOrderlogList($condition) {
        return db('orderlog')->where($condition)->select();
    }

    /**
     * 取得单条订单操作记录
     * @access public
     * @author csdeshang
     * @param array $condition 条件     
     * @param string $order 排序
     * @return array
     */
    public function getOrderlogInfo($condition = array(), $order = '') {
        return db('orderlog')->where($condition)->order($order)->find();
    }

    /**
     * 返回是否允许某些操作
     * @access public
     * @author csdeshang
     * @param type $operate 操作
     * @param type $order_info 订单信息
     * @return boolean
     */
    public function getOrderOperateState($operate, $order_info) {
        if (!is_array($order_info) || empty($order_info))
            return false;

        switch ($operate) {
            //买家取消订单 10  20
            case 'buyer_cancel':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                break;

            //申请退款
            case 'refund_cancel':
                if (isset($order_info['refund'])) {
                    $state = $order_info['refund'] == 1 && !intval($order_info['lock_state']);
                    if($order_info['ob_no']){//已结算不可以退款
                        $state = FALSE;
                    }
                } else {
                    $state = FALSE;
                }
                break;

            //商家取消订单
            case 'store_cancel':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' &&
                        in_array($order_info['order_state'], array(ORDER_STATE_PAY, ORDER_STATE_SEND)));
                break;

            //平台取消订单
            case 'system_cancel':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                break;

            //平台收款
            case 'system_receive_pay':
                $state = $order_info['order_state'] == ORDER_STATE_NEW && $order_info['payment_code'] == 'online';
                break;

            //买家投诉
            case 'complain':
                $state = in_array($order_info['order_state'], array(ORDER_STATE_PAY, ORDER_STATE_SEND)) ||
                        intval($order_info['finnshed_time']) > (TIMESTAMP - config('complain_time_limit'));
                break;

            case 'payment':
                $state = $order_info['order_state'] == ORDER_STATE_NEW && $order_info['payment_code'] == 'online';
                break;

            //调整运费
            case 'modify_price':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) || ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                $state = floatval($order_info['shipping_fee']) > 0 && $state;
                break;
            //调整商品价格
            case 'spay_price':
                $state = ($order_info['order_state'] == ORDER_STATE_NEW) ||
                        ($order_info['payment_code'] == 'offline' && $order_info['order_state'] == ORDER_STATE_PAY);
                $state = floatval($order_info['goods_amount']) > 0 && $state;
                break;

            //发货
            case 'send':
                $state = !$order_info['lock_state'] && $order_info['order_state'] == ORDER_STATE_PAY;
                break;

            //收货 30
            case 'receive':
                $state = $order_info['order_state'] == ORDER_STATE_SEND;
                break;

            //评价
            case 'evaluation': 
                $state = !$order_info['refund_state'] && !$order_info['lock_state'] && !$order_info['evaluation_state'] && $order_info['order_state'] == ORDER_STATE_SUCCESS;
                break;

            //锁定
            case 'lock':
                $state = intval($order_info['lock_state']) ? true : false;
                break;

            //快递跟踪
            case 'deliver':
                $state = !empty($order_info['shipping_code']) && in_array($order_info['order_state'], array(ORDER_STATE_SEND, ORDER_STATE_SUCCESS));
                break;

            //放入回收站
            case 'delete':
                $state = in_array($order_info['order_state'], array(ORDER_STATE_CANCEL, ORDER_STATE_SUCCESS)) && $order_info['delete_state'] == 0;
                break;

            //永久删除、从回收站还原
            case 'drop':
            case 'restore':
                $state = in_array($order_info['order_state'], array(ORDER_STATE_CANCEL, ORDER_STATE_SUCCESS)) && $order_info['delete_state'] == 1;
                break;
        }
        return $state;
    }

    /**
     * 联查订单表订单商品表
     * @access public
     * @author csdeshang
     * @param array $condition 条件
     * @param string $field 站点
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function getOrderAndOrderGoodsList($condition, $field = '*', $page = 0, $order = 'rec_id desc') {
        if($page){
            $list = db('ordergoods')->alias('order_goods')->where($condition)->field($field)->join('__ORDER__ order','order_goods.order_id=order.order_id','LEFT')->paginate($page,false,['query' => request()->param()]);
            $this->page_info = $list;
            return $list->items();
        }else{
            $list = db('ordergoods')->alias('order_goods')->where($condition)->field($field)->join('__ORDER__ order','order_goods.order_id=order.order_id','LEFT')->select();
            return $list;
        }
    }

    /**
     * 订单销售记录 订单状态为20、30、40时
     * @access public
     * @author csdeshang
     * @param unknown $condition  条件  
     * @param string $field 字段
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function getOrderAndOrderGoodsSalesRecordList($condition, $field = "*", $page = 0, $order = 'rec_id desc') {
        $condition['order_state'] = array('in', array(ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS));
        return $this->getOrderAndOrderGoodsList($condition, $field, $page, $order);
    }

    /**
     * 获取退换货商品信息
     * @access public
     * @author csdeshang
     * @param unknown $condition  条件  
     * @param string $field 字段
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function getReturnOrderInfo($condition, $field = "*", $page = 0, $order = 'rec_id desc') {
        $order_info = db('order')->alias('o')
                                 ->join('ordergoods g','g.order_id = o.order_id')
                                 ->field($field)
                                 ->where($condition)
                                 ->order($order)
                                 ->find();
        return $order_info;                         
    }

   /**
     * 获取退换货入库
     * @access public
     * @author csdeshang
     * @param unknown $condition  条件  
     * @param string $field 字段
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function addReturnOrder($order_id,$apply_type,$apply_reason,$apply_explain,$user_id,$order_info,$express_id,$invoice_no,$goods_id,$rec_id,$apply_images) {
        
        if (!is_array($order_info) || empty($order_info))
            return false;
        //判断重复提交
        $where['rec_id'] = $rec_id;
        $tag = db('ordergoods')->where($where)->find();
        if($tag['fail_status'] == 2 || $tag['fail_status'] == 3 || $tag['fail_status'] == 4){
            return json_fail_return('审核失败，无法重复提交');
        }
        if($tag['return_status'] > 0 && $tag['return_status'] != 7){
            return json_fail_return('已有数据无需重复提交');
        }
        //判断发货状态
        switch ($order_info['order_state']) {
            case 20:
                $goods_state = 1;
                break;
            case 30:
                $goods_state = 2;
                break;
            case 40:
                $goods_state = 4;
                break;        
            default:
                break;
        }
        //将图片转为json存起来
        $pic_info = json_encode($apply_images);

        $data = [
           'order_id' => $order_id,
           'order_sn' => $order_info['order_sn'],
           'refund_sn' => 'S'. rand(0,1000000),
           'store_id' => $tag['store_id'],
           'store_name' => $order_info['store_name'],
           'buyer_id' => $user_id,
           'buyer_name' => $order_info['buyer_name'],
            'goods_id' => $goods_id,
           'order_goods_id' => $rec_id,
           'goods_name' => $tag['goods_name'],
           'goods_num' => $tag['goods_num'],
           'goods_image' => $tag['goods_image'],
           'refund_type' => $apply_type,
           'goods_state' =>  $goods_state,
           'add_time' => time(),
           'reason_info' => $apply_explain,
           'pic_info' => $pic_info,
           'buyer_message' => $apply_reason,
           'express_id' => $express_id,
           'invoice_no' => $invoice_no,
           'yys_id' => $order_info['yys_id'],
           'app_order_id' => $order_info['apporder_id'],
           // 'refund_state' => $apply_type,
        ];
        //判断是否需要退货
        if($apply_type == 1){
            //子订单退款
            $data['return_type'] = 1;
            $data['refund_amount'] = $order_info['order_amount'];
            $data['app_order_id'] = $order_info['apporder_id'];
        }else{
            //退换货
            $data['return_type'] = 2;
            $data['refund_amount'] = $tag['goods_pay_price'];
        }
        $res = db('refundreturn')->insertGetId($data);

        //用于前端判断是否显示退换货，修改状态

        if($apply_type == 1){
            //子订单退款
           db('ordergoods')->where(['order_id'=>$order_id])->update(['return_status'=>1]);
           return db('order')->where(['order_id'=>$order_id])->update(['refund_state'=>1]);        
        }elseif($apply_type == 2){
            //添加订单日志  退货
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户发起退货，退货原因：'.$apply_reason;
            $data['log_user'] = $order_info['buyer_name'];
            $data['log_orderstate'] = 30;
            model('order')->addOrderlog($data);
            return db('ordergoods')->where(['rec_id'=>$rec_id])->update(['return_status'=>2]);
        }else{
            //添加订单日志  换货
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户发起换货，换货原因：'. $apply_reason;
            $data['log_user'] = $order_info['buyer_name'];
            $data['log_orderstate'] = 30;
            model('order')->addOrderlog($data);
            return db('ordergoods')->where(['rec_id'=>$rec_id])->update(['return_status'=>3]);
        }
    }

        /**
     * 大订单全部退款
     * @access public
     * @author csdeshang
     * @param unknown $condition  条件  
     * @param string $field 字段
     * @param number $page 分页
     * @param string $order 排序
     * @return array
     */
    public function addBigRefundOrder($app_order_id,$apply_type,$apply_reason,$apply_explain,$user_id,$app_order_info,$pic_info) {
        
        //判断重复提交
        $where['app_order_id'] = $app_order_id;
        $where['refund_type'] = $apply_type;

        $tag = db('refundreturn')->where($where)->find();
        if(!empty($tag) && $tag['return_del'] == 0){
            return json_fail_return('已有数据无需重复提交');
        }

        //获取多商户的信息
        $goods = explode(',', $app_order_info['goods_ids']);
        foreach ($goods as $key => $value) {
            $store = db('goods')->where(['goods_id'=>$value])->field('store_id,store_name,goods_name,goods_image')->find();
            $new_store[] = $store;
        }
        $store_id = array_column($new_store,'store_id');
        $new_store_id = array_unique($store_id);
       
        $store_name = array_column($new_store,'store_name');
        $new_store_name = array_unique($store_name);
        
        $goods_name = array_column($new_store,'goods_name');
        $new_goods_name = array_unique($goods_name);
        
        $goods_image = array_column($new_store,'goods_image');
        $new_goods_image = array_unique($goods_image);

        //運營商id

        $order_info = db('order')->where(['order_id'=>$app_order_info['order_ids']])->find();



        $data = [
           'app_order_id' => $app_order_id,
           'order_id' => $app_order_info['order_ids'],
           'order_sn' => $app_order_info['order_sn'],
           'refund_sn' => 'S'. rand(0,1000000),
           'store_id' => implode(',', $new_store_id),
           'store_name' => implode(',', $new_store_name),
           'buyer_id' =>   $app_order_info['user_id'],
           'buyer_name' => $app_order_info['user_name'],
           'goods_id' => $app_order_info['goods_ids'],
           'goods_name' => implode(',', $new_goods_name),
           'refund_amount' => $app_order_info['price'],
           'goods_image' => implode(',', $new_goods_image),
           'refund_type' => $apply_type,
           'goods_state' =>  2,
           'add_time' => time(),
           'reason_info' => $apply_explain,
           'pic_info' => $pic_info,
           'buyer_message' => $apply_reason,
           'goods_state' => 2,
           'yys_id' => $order_info['yys_id'],
           'app_sn' => $app_order_info['order_sn']
        ];
       
        //修改所有子订单的状态、
        $order_ids = explode(',',$app_order_info['order_ids']);
        foreach ($order_ids as $key => $value) {
             //修改大订单状态为2
             db('order')->where(['order_id'=>$value])->update(['refund_state'=>1]);
        }
        
        //修改大订单退款状态
        db('app_order')->where(['app_order_id'=>$app_order_id])->update(['refund_price'=>1]);


  
        #处理商城订单退款统计
        $stat_model = new \app\common\model\Stat();
        $statis_data = [
            'os_order_returntotals' => $app_order_info['price']
        ];
        $stat_model->generateReturnMall($statis_data);

        #处理店铺退款统计
        $store_data = [
            'ob_order_return_totals' => $app_order_info['price'],
            'ob_store_id' => implode(',', $new_store_id)
        ];
        $stat_model->generateReturnStoreMall($store_data);


        return db('refundreturn')->insertGetId($data);
    }


    /**
     * 取得订单列表(所有)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function get_OrderprojectList($condition, $page = '', $order = 'op.order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('orderproject')->alias('op')
                ->join('order o','o.orderproject_id=op.order_id')
                ->where($condition)
                ->field('op.*,o.order_state as zhu_order_state,o.orderproject_id')
                ->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('orderproject')->where($condition)->order($order)->limit($limit)->select();
        }

        if (empty($list))
            return array();
        $order_list = array();
        if (empty($order_list))
            $order_list = $list;
        return  $order_list;
    }

        /**
     * 取得订单列表(所有)
     * @access public
     * @author csdeshang
     * @param unknown $condition 条件
     * @param string $page 分页
     * @param string $field 字段
     * @param string $order 排序
     * @param string $limit 限制
     * @param unknown $extend 追加返回那些表的信息,如array('order_common','order_goods','store')
     * @return Ambigous <multitype:boolean Ambigous <string, mixed> , unknown>
     */
    public function get_ProjectorderList($condition, $page = '', $order = 'order_id desc', $limit = '', $extend = array()) {
        if($page){
            $list_paginate = db('orderproject')
                ->where($condition)
                ->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $list_paginate;
            $list = $list_paginate->items();
        }else{
            $list = db('orderproject')->where($condition)->order($order)->limit($limit)->select();
        }

        if (empty($list))
            return array();
        $order_list = array();
        if (empty($order_list))
            $order_list = $list;
        return  $order_list;
    }


    /**
     * 取单个品牌内容
     * @access public
     * @author csdeshang
     * @param array $condition 检索条件
     * @param string $field 字段
     * @return array
     */
    public function getBrandInfo($condition, $field = '*') {
        return db('goodsproject')->field($field)->where($condition)->find();
    }

      /**
     * 取单个品牌内容
     * @access public
     * @author lihe
     * @return array
     */
    public function autoReceiptOrder()
    {
        $limitTime = date('Y-m-d',strtotime('-7 day'));
        $orders = db('order')->alias('o')
                ->join('ordercommon c','o.order_id=c.order_id')
                ->where('o.order_state', 30)
                ->where('c.shipping_time', '>', $limitTime)
                ->field('o.order_id')
                ->select();
        if($orders){
            $orderIds = [];
            foreach($orders as $order){
                $orderIds[] = $order['order_id'];
            }
            $update = array(
                'order_state' => 40
            );
            db('order')->where('order_id', 'in', $order_ids)->update($update);
        
            //do 大订单号 修改
            $appOrders = db('app_order')->where('order_status', 1)->field('app_order_id,order_ids')->select();
            if($appOrders){
                foreach($orderIds as $orderid){//循环每个订单号
                    foreach($appOrders as $appOrder){//循环每个大订单号
                        $appOrderIds = explode(',', $appOrder['order_ids']);//拿出小订单号集合
                        if(in_array($orderid, $appOrderIds)){
                            $noReceiptOrder = db('order')->where('order_id', 'in', $appOrderIds)->where('order_state', '<>', 40)->select();//查找是否有未接单的
                            if(!$noReceiptOrder){
                                  db('app_order')->where('app_order_id', $appOrder['app_order_id'])->update(['order_status' => 2]);  
                            }
                            break;    
                        }
                    }
                }
            }

            return count($orderIds).'个订单需要自定收货，分别是:'.implode(',', $orderIds);
        } 
        
        return '没有订单需要收货！';
    }

}